package io.kiki.sba.registry.server.clientInterface.wrapper;

import io.kiki.sba.registry.common.model.store.BaseInfo;
import io.kiki.sba.registry.common.model.wrapper.WrapperInterceptor;
import io.kiki.sba.registry.common.model.wrapper.WrapperInvocation;
import io.kiki.sba.registry.server.clientInterface.limit.AccessLimitService;
import org.springframework.beans.factory.annotation.Autowired;


public class AccessLimitWrapperInterceptor implements WrapperInterceptor<RegisterInvokeData, Boolean> {

    @Autowired
    private AccessLimitService accessLimitService;

    @Override
    public Boolean invokeCodeWrapper(WrapperInvocation<RegisterInvokeData, Boolean> wrapperInvocation) throws Exception {

        RegisterInvokeData registerInvokeData = wrapperInvocation.getParameterSupplier().get();
        BaseInfo baseInfo = (BaseInfo) registerInvokeData.getStoreData();

        if (!accessLimitService.tryAcquire()) {
            throw new RuntimeException(String.format("Register access limit for session server!dataInfoId=%s,connectId=%s", baseInfo.getDataInfoId(), baseInfo.getClientUrl()));
        }

        return wrapperInvocation.proceed();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
